<template>
  <div v-if="goodsNum === 0">
    <van-empty image="search" description="购物车为空" />
  </div>
  <div v-else>
    <div class="goodsTop">
      <h2>购物车</h2>
    </div>
    <div class="goodsCenter">
      <div class="goodsItem" v-for="(item, index) in goodsData" :key="index">
        <div class="left">
          <img :src="item.img">
        </div>
        <div class="center">{{item.title}}</div>
        <div class="right"><van-stepper v-model="item.cartCount" theme="round" button-size="22" disable-input min="0" step="0" @plus="add(item)" @minus="sub(item)"/></div>
      </div>
    </div>
    <div class="goodsBottom">
      <van-button plain hairline type="info" color="grey" @click="clickButton(1)">下单</van-button>
      <van-button plain hairline type="info" color="grey"  @click="clickButton(0)">清空</van-button>
    </div>
  </div>
</template>
<script lang="ts">
import { useStore } from 'vuex';
import {defineComponent, ref, computed, getCurrentInstance} from 'vue';
export default defineComponent({
  name:'ShopCart',
  setup() {
    const {proxy}: any = getCurrentInstance()
    const store = useStore()
    const value = 0
    const goodsNum = ref(
      computed(() => {
        return store.getters.getGoodsNum
      })
    )
    // 获取当前购物车中的所有数据
    const goodsData = ref(
      computed (() => {
        return store.state.cartarray
      })
    )
    function clickButton (value: any) {
      if (value === 1) {
        proxy.$toast.success('下单成功')
      } else if (value === 0) {
        store.commit('clearCart')
      }
    }
    function add (val: any) {
      store.commit('add', val)
    }
    function sub (val: any) {
      store.commit('sub', val)
    }
    return {
      goodsNum,
      value,
      goodsData,
      clickButton,
      add,
      sub
    }
  }
})
</script>
<style scoped>
.goodsTop {
  margin-top: 3rem;
  margin-bottom: 2rem;
}
.goodsItem {
  position: relative;
  width: 100%;
  height: 5rem;
  margin-top: 1rem;
}
img {
  height: 100%;
}
.goodsCenter {
  position: relative;
  width: 100%;
  min-height: 5rem;
}
.left {
  height: 5rem;
  position: absolute;
  left: 1rem;
}
.center {
  position: absolute;
  top: 0.5rem;
  right: 1.5rem;
}
.right {
  position: absolute;
  bottom: 0.5rem;
  right: 1.5rem;
}
.goodsBottom {
  margin-top: 2rem;
  margin-bottom: 5rem;
}
</style>
